<template>
  <div class="container">
    <div class="div_box">
      <!-- <div style="position: relative;z-index: 9999;">
        <el-tooltip
            effect="dark"
            content="点击设置告警声音"
            placement="top-end"
            :hide-after="1000"
                          >
                            <el-image :src="sy2" style="width: 16px; height: 16px;"></el-image>
                          </el-tooltip>
                          <div class="audio-box">
                          <p @click="audioOdinary">普通</p>
                          <p @click="audioExclusive">专属</p>
                        </div>
                      </div> -->

      <div style="z-index: 999">
        <el-tooltip
          effect="dark"
          content="点击打开声音"
          placement="top-end"
          :hide-after="1000"
          v-if="!isAudio"
        >
          <el-image
            :src="sy1"
            style="width: 18px; height: 18px; cursor: pointer"
            @click="audioSwitch"
          ></el-image>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          content="点击关闭声音"
          placement="top-end"
          :hide-after="1000"
          v-else
        >
          <el-image
            :src="sy2"
            style="width: 18px; height: 18px; cursor: pointer"
            @click="audioSwitch"
          ></el-image>
        </el-tooltip>
      </div>

      <div style="z-index: 999">
        <el-tooltip
          v-if="alarmDialogType == 'close'"
          effect="dark"
          content="点击打开告警弹窗"
          placement="top-end"
          :hide-after="1000"
        >
          <el-image
            :src="gj2"
            style="width: 18px; height: 18px; cursor: pointer"
            @click="alarmDialogOpen"
          ></el-image>
        </el-tooltip>
        <el-tooltip
          v-else
          effect="dark"
          content="点击关闭告警弹窗"
          placement="top-end"
          :hide-after="1000"
        >
          <el-image
            :src="gj1"
            style="width: 18px; height: 18px; cursor: pointer"
            @click="alarmDialogClose"
          ></el-image>
        </el-tooltip>
      </div>
    </div>

    <div class="div_box2">
      <div>
        <el-tooltip
          effect="dark"
          content="点击关闭连续告警提示"
          placement="top-end"
          :hide-after="1000"
          v-if="isVoice"
        >
          <el-image
            :src="ContinuousAlarm"
            style="width: 22px; height: 22px; cursor: pointer"
            @click="voiceSwitch"
          ></el-image>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          content="点击开启连续告警提示"
          placement="top-end"
          :hide-after="1000"
          v-else
        >
          <el-image
            :src="discontinuousAlarm"
            style="width: 22px; height: 22px; cursor: pointer"
            @click="voiceSwitch"
          ></el-image>
        </el-tooltip>
      </div>
    </div>

    <div class="title">实时告警</div>
    <div class="warnData-item">
      <transition-group
        class="list"
        name="myGroup"
        tag="div"
        v-show="projectData.length >= 1"
      >
        <div class="item" v-for="(item, index) in projectData" :key="index">
          <div style="font-size: 12px">
            <div class="item_title" v-if="item.status == 1">
              <div>
                <span style="margin-right: 15px; color: #fc3758">未处理</span>
                <span>
                  {{ item.deviceType | deviceTypeText }}
                  <!-- {{ deviceTypeText(item.deviceType) }} -->
                </span>
              </div>
              <div style="color: #d1d1d1">{{ item.createTime }}</div>
            </div>

            <div class="item_title2" v-else-if="item.status == 2">
              <div>
                <span style="margin-right: 15px; color: #f08027">处理中</span>
                <span>
                  {{ item.deviceType | deviceTypeText }}
                  <!-- {{ deviceTypeText(item.deviceType) }} -->
                </span>
              </div>

              <div style="color: #d1d1d1">{{ item.createTime }}</div>
            </div>

            <div class="item_title3" v-else-if="item.status == 3">
              <div>
                <span style="margin-right: 15px; color: #1ed964">已处理</span>
                <span>
                  {{ item.deviceType | deviceTypeText }}
                  <!-- {{ deviceTypeText(item.deviceType) }} -->
                </span>
              </div>

              <div style="color: #d1d1d1">{{ item.createTime }}</div>
            </div>
          </div>

          <div class="item_box">
            <div style="display: flex; align-items: center; width: 82%">
              <div style="width: 28px; height: 28px; margin-right: 10px">
                <el-image :src="didianya" v-if="item.alarmType == 1"></el-image>
                <el-image
                  :src="sbcc"
                  v-else-if="item.alarmType == 2"
                ></el-image>
                <el-image
                  :src="mendakai"
                  v-else-if="item.alarmType == 3"
                ></el-image>
                <el-image
                  :src="jchd"
                  v-else-if="item.alarmType == 4"
                ></el-image>
                <el-image
                  :src="Frame322"
                  v-else-if="item.alarmType == 5"
                ></el-image>
                <el-image :src="gz" v-else-if="item.alarmType == 6"></el-image>
                <el-image
                  :src="yanganguzhang"
                  v-else-if="item.alarmType == 7"
                ></el-image>
                <el-image
                  :src="wdgz"
                  v-else-if="item.alarmType == 8"
                ></el-image>
                <el-image
                  :src="guzhangchaichu"
                  v-else-if="item.alarmType == 9"
                ></el-image>
                <el-image
                  :src="wdgj"
                  v-else-if="item.alarmType == 10"
                ></el-image>
                <el-image
                  :src="dndgj"
                  v-else-if="item.alarmType == 11"
                ></el-image>
                <el-image
                  :src="gndgj"
                  v-else-if="item.alarmType == 12"
                ></el-image>
                <el-image
                  :src="guanmen"
                  v-else-if="item.alarmType == 13"
                ></el-image>
                <el-image
                  :src="poweroutagealert"
                  v-else-if="item.alarmType == 14"
                ></el-image>
                <el-image
                  :src="batterylow"
                  v-else-if="item.alarmType == 15"
                ></el-image>
                <el-image
                  :src="poorCommunicationSignal"
                  v-else-if="item.alarmType == 16"
                ></el-image>
                <el-image
                  :src="messageReportingFailure"
                  v-else-if="item.alarmType == 17"
                ></el-image>
                <el-image
                  :src="networkInitializationFailure"
                  v-else-if="item.alarmType == 18"
                ></el-image>
                <el-image
                  :src="pressureBelowLimit"
                  v-else-if="item.alarmType == 19"
                ></el-image>
                <el-image
                  :src="pressureAboveLimit"
                  v-else-if="item.alarmType == 20"
                ></el-image>
                <el-image
                  :src="pressureFluctuationAboveLimit"
                  v-else-if="item.alarmType == 21"
                ></el-image>
                <el-image
                  :src="pressureSensorFailure"
                  v-else-if="item.alarmType == 22"
                ></el-image>
                <el-image
                  :src="NBLowpower"
                  v-else-if="item.alarmType == 23"
                ></el-image>
                <el-image
                  :src="humiture"
                  v-else-if="item.alarmType == 24"
                ></el-image>
                <el-image
                  :src="selfinspection"
                  v-else-if="item.alarmType == 25"
                ></el-image>
                <el-image
                  :src="waterLogging"
                  v-else-if="item.alarmType == 26"
                ></el-image>
                <el-image
                  :src="gndgj"
                  v-else-if="item.alarmType == 27"
                ></el-image>
                <el-image
                  :src="gndgj"
                  v-else-if="item.alarmType == 28"
                ></el-image>
                <el-image
                  :src="gndgj"
                  v-else-if="item.alarmType == 30"
                ></el-image>
                <el-image
                  :src="gndgj"
                  v-else-if="item.alarmType == 31"
                ></el-image>
                <el-image
                  :src="gndgj"
                  v-else-if="item.alarmType == 32"
                ></el-image>
                <el-image :src="gndgj" v-else></el-image>
              </div>
              <div style="display: flex; flex-direction: column; width: 82%">
                <span
                  style="
                    font-size: 16px;
                    font-weight: 500;
                    width: 98%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  "
                  >{{ item.orgName }}

                  <span style="font-size: 12px">
                    {{ item.alarmType | alarmTypeText }}
                  </span>
                </span>
                <span
                  style="
                    margin-top: 8px;
                    width: 98%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  "
                  >{{ item.name }}</span
                >
              </div>
            </div>
            <div @click="warnHandleClick(item)" v-if="item.status == '1'">
              处理
            </div>
            <div @click="warnHandleClick(item)" v-else>查看</div>
          </div>
        </div>
      </transition-group>
      <transition name="fade" mode="out-in">
        <div v-show="projectData.length <= 0" class="no-warn-info">
          <img :src="wugj" />
          <div>暂无告警</div>
        </div>
      </transition>
    </div>

    <WarnHandle
      :alarmInfo="alarmInfo"
      ref="refWarnHandle"
      @updateAlarmList="updateAlarmList"
      @clickflag="clickflag"
    >
    </WarnHandle>

    <processingRecord
      ref="refprocessingRecord"
      :alarmInfo="alarmInfo"
      @clickWarnHandle="clickWarnHandle"
      @updateAlarmList2="updateAlarmList2"
      @particulars="particulars"
    ></processingRecord>

    <Ichnography ref="refIchnography"></Ichnography>

    <rightDialog
      ref="refrightDialog"
      :dialogAlarmInfo="dialogAlarmInfo"
      :isVoice="isVoice"
      @updateAlarmList="updateAlarmList"
      @clickflag="clickflag"
    ></rightDialog>
    <alarmDialog
      ref="refalarmDialog"
      :dialogAlarmInfo="dialogAlarmInfo"
      :isAudio="isAudio"
      :alarmDialogFlag="alarmDialogFlag"
      @pauseAudio="pauseAudio"
      @onplayAudio="playAudio"
    ></alarmDialog>
  </div>
</template>

<script>
// import "@/utils/mqttws31.js";
import mqtt from "mqtt"; //index.html引入的已弃用
// var {  Client,  Message } = require('./mqtt.js');
import { reqClient } from "@api/apiDatav.js";
import { reqAlarmList, reqDetectorProductList } from "@/api/api";
import { reqFloorById } from "@api/api.js";
import WarnHandle from "./WarnHandle.vue";
import processingRecord from "./processingRecord.vue";
import { mapState } from "vuex";
import Ichnography from "../components/Ichnography.vue";
import rightDialog from "./rightDialog.vue";
import alarmDialog from "./alarmDialog.vue"; //告警弹窗
const speechHandle = window.speechSynthesis;
const speechMsg = new SpeechSynthesisUtterance();

export default {
  components: {
    WarnHandle,
    processingRecord,
    Ichnography,
    rightDialog,
    alarmDialog,
  },
  data() {
    return {
      img: require("@assets/images/xiaofang.png"),
      item_title: "item_title", //动态class样式
      sy1: require("@assets/images/datav/sy1.png"),
      sy2: require("@assets/images/datav/sy2.png"),
      ContinuousAlarm: require("@assets/images/datav/ContinuousAlarm.png"),
      discontinuousAlarm: require("@assets/images/datav/discontinuousAlarm.png"),
      gj1: require("@assets/images/datav/gj1.png"),
      gj2: require("@assets/images/datav/gj2.png"),
      gjtc: require("@assets/images/datav/gjtc.png"),
      didianya: require("@assets/images/datav/didianya.png"),
      sbcc: require("@assets/images/datav/sbcc.png"),
      mendakai: require("@assets/images/datav/mendakai.png"),
      jchd: require("@assets/images/datav/jchd.png"),
      Frame322: require("@assets/images/datav/Frame322.png"),
      gz: require("@assets/images/datav/gz.png"),
      yanganguzhang: require("@assets/images/datav/yanganguzhang.png"),
      wdgz: require("@assets/images/datav/wdgz.png"),
      guzhangchaichu: require("@assets/images/datav/guzhangchaichu.png"),
      wdgj: require("@assets/images/datav/wdgj.png"),
      dndgj: require("@assets/images/datav/dndgj.png"),
      gndgj: require("@assets/images/datav/gndgj.png"),
      guanmen: require("@assets/images/datav/guanmen.png"),
      pressureSensorFailure: require("@assets/images/datav/pressure sensor failure.png"),
      selfinspection: require("@assets/images/datav/self-inspection.png"),
      waterLogging: require("@assets/images/datav/waterLogging.png"),
      NBLowpower: require("@assets/images/datav/NBLowpower.png"),
      humiture: require("@assets/images/datav/humiture.png"),
      pressureFluctuationAboveLimit: require("@assets/images/datav/pressure fluctuation above limit.png"),
      pressureAboveLimit: require("@assets/images/datav/pressure above limit.png"),
      pressureBelowLimit: require("@assets/images/datav/pressure below limit.png"),
      networkInitializationFailure: require("@assets/images/datav/networkInitializationFailure.png"),
      messageReportingFailure: require("@assets/images/datav/messageReportingFailure.png"),
      poorCommunicationSignal: require("@assets/images/datav/poorCommunicationSignal.png"),
      poweroutagealert: require("@assets/images/datav/poweroutagealert.png"),
      batterylow: require("@assets/images/datav/batterylow.png"),
      wugj: require("@assets/images/datav/wugj.png"),
      dataList: [
        {
          id: 0,
          time: "2022-12-11 11:02:50",
          address: "深圳市南山区京基御景峰1601",
          type: 1,
          status: 0,
        },
      ],
      projectData: [],
      showLoading: true,
      isLoading: false, //loading加载
      // 实时告警开始
      instanceId: "post-cn-7mz2d28ne0e", //实例 ID
      host: "post-cn-7mz2d28ne0e.mqtt.aliyuncs.com",
      port: 443, //WebSocket 协议服务端口，如果是走 HTTPS，设置443端口   ||80
      // topic: `alarm/${this.user.userId}`, //需要操作的 Topic,第一级父级 topic
      topic: `alarm/${this.$store.state.user.userId}`, //需要操作的 Topic,第一级父级 topic
      useTLS: true, //是否走加密 HTTPS，如果走 HTTPS，设置为 true
      cleansession: true,
      clientId: this.$store.state.datav.clientId || "", //GroupId@@@DeviceId，由 Group ID 和自己指定的 Device ID 组合构成
      mqtt: {},
      client: {},
      message: "",
      reconnectTimeout: 2000,
      username: this.$store.state.datav.mu || "",
      password: this.$store.state.datav.mp || "",
      isConnect: false, // 连接中断
      failConnect: false, // 连接失败
      // 实时告警结束
      audio: new Audio(),
      audioType: "odinary", //铃声状态--普通/专属/关闭
      isPlayNextAudio: false, //是否播放下一个音频
      disConnectPjtId: "", //连接断开时
      infoSent: false, //监视告警信息发送

      dialogVisible: false, //告警弹窗是否弹出
      dialogAlarmInfo: {}, //告警弹窗信息对象
      alarmHandleFlag: false, //告警处理标志--是否弹出告警弹窗
      showAudioChange: false, //告警声音选择是否展示
      alarmDialogType: "open", //告警弹窗类型--默认开启 open close

      /* 视频开始 */
      isVideo: false, //是否展示视频
      isClose: false, //是否显示关闭视频按钮
      // videoSrc: "https://video.beibeibang.com.cn/B01SC691.mp4",
      videoSrc: "",
      videoImg: "",
      preload: "auto", //  建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
      controls: true, // 确定播放器是否具有用户可以与之交互的控件。没有控件，启动视频播放的唯一方法是使用autoplay属性或通过Player API。
      autoplay: true,
      /* 视频结束 */
      alarmInfo: "", //告警处理所需信息
      isAudio: true, //告警声音
      isVoice: true,
      flag: true, //滚动条不用弹出新的告警
      alarmDialogFlag: true,
      audioList: [],
    };
  },
  computed: {
    ...mapState(["datav", "user", "spacesManage"]),
  },
  watch: {
    // "datav.clientId"(c) {
    //   // console.log(c, "cccc");
    //   // this.clientId = this.$store.state.datav.clientId;
    //   // this.username = this.$store.state.datav.mu;
    //   // this.password = this.$store.state.datav.mp;
    //   // this.MQTTconnect();
    // },
  },
  methods: {
    //  async deviceTypeText(deviceType) {
    //   this.$nextTick(async()=>{
    //     let namealarm=''
    //           let res = await reqDetectorProductList();
    //           if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
    //           this.detectorProductList = res.data.list;
    //           this.detectorProductList.push({
    //               detectorType:"DoorMagnetism",
    //               name:"门磁"
    //           },{
    //               detectorType:"Camera",
    //               name:"摄像机"
    //           },{
    //               detectorType:"GasSensor",
    //               name:"燃气"
    //           },{
    //               detectorType:"Infrared",
    //               name:"红外"
    //           },{
    //               detectorType:"SmokeAlarm",
    //               name:"烟感"
    //           },{
    //               detectorType:"FireHydrant",
    //               name:"消防水压"
    //           },{
    //               detectorType:"TemperatureAlarm",
    //               name:"温感"
    //           },{
    //               detectorType:"WaterSensor",
    //               name:"水浸"
    //           },{
    //               detectorType:"PressureGauge",
    //               name:"无线数字压力表"
    //           },{
    //               detectorType:"TankGauge",
    //               name:"无线数字液位表"
    //           },{
    //               detectorType:"UserTransferDevice",
    //               name:"用户传输装置"
    //           },{
    //               detectorType:"ElectricalMeasurement",
    //               name:"电气测控装置"
    //           },{
    //               detectorType:"FaultArc",
    //               name:"故障电弧探测器"
    //           },{
    //               detectorType:"SoundLightVoiceAlarm",
    //               name:"声光报警器"
    //           },{
    //               detectorType:"FireAlarmController",
    //               name:"火灾报警控制器"
    //           },)
    //           this.detectorProductList.forEach(item=>{
    //               if(item.detectorType==deviceType){
    //                   namealarm=item.name
    //               }
    //           })
    //           console.log(namealarm,'namealarm');
    //     return namealarm;
    //   })

    //   },
    // 查看平面图
    async clickIchnography() {
      const res = await reqFloorById(this.dialogAlarmInfo.spaceId);
      // console.log(res);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      if (res.data.rows.image == "")
        return this.$modal.notifyWarning("当前楼层暂无平面图,请上传后操作!");
      this.$refs.refIchnography.dialogVisible = true;
      this.$refs.refIchnography.getimage(res.data.rows.image);
      this.$refs.refIchnography.getGetMark(this.dialogAlarmInfo.spaceId);
    },
    clickWarnHandle() {
      this.$refs.refWarnHandle.dialogVisible = true;
    },

    particulars() {
      this.$refs.refalarmDialog.dialogVisible = true; //告警弹窗
      this.alarmDialogFlag = !this.alarmDialogFlag;
      // this.$refs.refrightDialog.AlarmDialogVisible=true;//告警弹窗
      // this.$refs.refrightDialog.getAlarmPlay(this.dialogAlarmInfo.id) // 告警id查询告警视频列表回放
      // this.$refs.refrightDialog.getFloorById(this.dialogAlarmInfo.spaceId) // 查询平面图
      // this.$refs.refrightDialog.getgetMark(this.dialogAlarmInfo.spaceId) // 获取平面图设备标点
      // this.$refs.refrightDialog.getByTargetId(this.dialogAlarmInfo.spaceId) // 安装点id获取接警人列表
      // this.$refs.refrightDialog.GetCamera(this.dialogAlarmInfo.spaceId) // 安装点查询摄像头
    },
    // 滚动条定位到最后一行
    scrollToBottom() {
      this.$nextTick(() => {
        let box = this.$el.querySelector(".warnData-item");
        // box.scrollTop = box.scrollHeight;// 滚动条定位到最后一行
        box.scrollTop = 0;
        // box.addEventListener('scroll', () => {
        //   const clientHeight = box.clientHeight;
        //   const scrollTop = box.scrollTop;
        //   const scrollHeight = box.scrollHeight;
        //   if (clientHeight + scrollTop === scrollHeight) {
        //     console.log('竖向滚动条已经滚动到底部')
        //     this.flag=true
        //   }else{
        //     console.log('没在底部')
        //     this.flag=false
        //   }
        // })
      });
    },
    // 控制铃声
    audioSwitch() {
      this.isAudio = !this.isAudio;
      // 弹窗关闭时单独控制铃声
      if (!this.isAudio) {
        this.pauseAudio(); // 停止铃声
      }
      // 响铃设置 :记住当前账号的设置 存储在本地浏览器
      let meterflag = true;
      this.audioList.forEach((item) => {
        if (item.id == this.user.userId) {
          meterflag = false;
          item.isAudio = this.isAudio;
          return;
        }
      });
      if (meterflag) {
        // 本地浏览器第一次设置
        this.audioList.push({
          id: this.user.userId,
          isAudio: this.isAudio,
        });
      }
      localStorage.setItem("audio", JSON.stringify(this.audioList));
      // if (this.audioType) {
      //   this.audio.src = "";
      //   this.isPlayNextAudio = false;
      // }
      // this.audioType = !this.audioType;
    },
    // 控制一直响铃
    voiceSwitch() {
      this.isVoice = !this.isVoice;
    },
    // 普通
    // async audioOdinary() {
    //   if (this.audioType == "odinary") {
    //     // 若已经是普通，则不做接口请求
    //     this.showAudioChange = false;
    //     return;
    //   }
    //   let params = {
    //     id: this.user.userId,
    //     receiveMode: 0,
    //   };
    //   const res = await reqUpdateReciveMode(params);
    //   this.showAudioChange = false;
    //   if (res.code !== 20000) return;
    //   // this.$message.success("已设置为普通告警语音");
    //   this.audioType = "odinary";
    //   this.$store.commit("saveReceiveMode", 0);
    //   if (this.audioType == "odinary") {
    //     this.audio.src = "";
    //     this.isPlayNextAudio = false;
    //   }
    //   this.textVoiceEnd();
    // },
    // // 专属
    // async audioExclusive() {
    //   if (this.audioType == "exclusive") {
    //     // 若已经是专属，则不做接口请求
    //     this.showAudioChange = false;
    //     return;
    //   }
    //   let params = {
    //     id: this.user.userId,
    //     receiveMode: 1,
    //   };
    //   const res = await reqUpdateReciveMode(params);
    //   this.showAudioChange = false;
    //   if (res.code !== 20000) return;
    //   // this.$message.success("已设置为专属告警语音");
    //   this.audioType = "exclusive";
    //   this.$store.commit("saveReceiveMode", 1);
    //   this.pauseAudio();
    // },
    // 播放铃声
    playAudio() {
      // console.log('播放');
      // this.audio.src =
      //   "https://gelivideo.oss-cn-shenzhen.aliyuncs.com/alarm.mp3";
        //   this.audio.src =
        // "https://img.tukuppt.com/newpreview_music/01/63/81/63b670a346fa034.mp3";
        this.audio.src = require("@/assets/audio/sound.mp3");
      this.audio.loop = this.isVoice;
      this.audio.play();
      //   this.audio
      // .play()
      // .then(() => {
      //   console.log(`autoplay well`);
      // })
      // .catch((e) => {
      //   console.log(`autoplay fail, wait for first click`);
      //   if (e instanceof DOMException) {
      //     // play before user intersact
      //     const autoPlayAfterAnyClick = () => {
      //       this.audio.src =
      //     "https://gelivideo.oss-cn-shenzhen.aliyuncs.com/alarm.mp3";
      //       this.audio.play();
      //       document.removeEventListener('click', autoPlayAfterAnyClick);
      //     };

      //     document.addEventListener('click', autoPlayAfterAnyClick);
      //     throw e;
      //   } else {
      //     // or rethrow
      //     throw e;
      //   }
      // });
    },
    // 停止铃声
    pauseAudio() {
      this.audio.src = "";
      this.audio.pause();
      this.isPlayNextAudio = false;
    },
    // 关闭弹窗
    async alarmDialogClose() {
      // this.showAudioChange = false;
      // if (this.alarmDialogType == "close") return; // 若已经是关，则不做接口请求

      // let params = {
      //   id: this.user.userId,
      //   receiveType: 0,
      // };
      // const res = await reqUpdateReciveType(params);
      // if (res.code !== 20000) return;
      // // this.$message.success("已设置为告警弹窗关闭");
      // this.$store.commit("saveReceiveType", 0);
      this.alarmDialogType = "close";
      // this.dialogVisible = false;
    },
    // 打开弹窗
    async alarmDialogOpen() {
      // this.showAudioChange = false;
      // if (this.alarmDialogType == "open") return; // 若已经是开，则不做接口请求

      // let params = {
      //   id: this.user.userId,
      //   receiveType: 1,
      // };
      // const res = await reqUpdateReciveType(params);
      // if (res.code !== 20000) return;
      // // this.$message.success("已设置为告警弹窗打开");
      // this.$store.commit("saveReceiveType", 1);
      this.alarmDialogType = "open";
    },
    // 关闭声音选择下拉和告警弹窗下拉选择
    closeAudioAndDialog() {
      this.showAudioChange = false;
    },
    // 重新连接
    reConnectBtn() {
      // this.MQTTconnect();
    },
    // MQTT中断函数    中断连接
    disconnect() {
      // console.log("中断连接");
      this.mqtt.disconnect(); //进行连接中断
    },
    // 监听连接断开时的状态
    onConnectionLost: function (response) {
      // console.log("监听连接断开时的状态");
      this.isConnect = false;
      this.failConnect = false;
    },

    // 时间戳转成日期格式： 年-月-日,时-分-秒
    timestampToTime2(timestamp) {
      if (timestamp === 0 || timestamp == null) {
        return "";
      } else {
        // var date = new Date(timestamp * 1000)// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var date = new Date(timestamp);
        var Y = date.getFullYear() + "-";
        var M =
          (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
        var D =
          date.getDate() < 10
            ? "0" + date.getDate() + " "
            : date.getDate() + " ";
        var H = date.getHours() + ":";
        var M2 =
          (date.getMinutes() < 10
            ? "0" + date.getMinutes()
            : date.getMinutes()) + ":";
        var S =
          date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return Y + M + D + H + M2 + S;
      }
    },

    /**
     * @name:  根据特殊符号 "&&"  分解省市区和详细地址  加 语音转换
     * @msg:
     * @return {*}
     */
    specialSymbolDecomposition(str) {
      let index = str.lastIndexOf("&&");
      str = str.substring(index + 2, str.length);
      let result = this.voiceNumberTrans(str);
      return result;
    },
    /**
     * @name:  语音播报读数转换：如：705转为七零五
     * @msg:
     * @return {*}
     */
    voiceNumberTrans(str) {
      str = str.split("");
      let arr = [];
      str.forEach((item) => {
        if (item == 0) {
          let a = parseInt(item);
          if (a === 0) {
            item = "零";
            arr.push(item);
          } else {
            arr.push(item);
          }
        } else if (item == 1) {
          item = "一";
          arr.push(item);
        } else if (item == 2) {
          item = "二";
          arr.push(item);
        } else if (item == 3) {
          item = "三";
          arr.push(item);
        } else if (item == 4) {
          item = "四";
          arr.push(item);
        } else if (item == 5) {
          item = "五";
          arr.push(item);
        } else if (item == 6) {
          item = "六";
          arr.push(item);
        } else if (item == 7) {
          item = "七";
          arr.push(item);
        } else if (item == 8) {
          item = "八";
          arr.push(item);
        } else if (item == 9) {
          item = "九";
          arr.push(item);
        } else {
          arr.push(item);
        }
      });
      return arr.join("");
    },
    /**
     * @name: 特殊符号去除   &&
     * @msg:
     * @return {*}
     */
    specialSymbolDelete(address) {
      address = address.replace(/&&/g, "");
      return address;
    },

    // loading加载
    inLoading() {
      this.isLoading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(7, 19, 86, 1)",
        target: document.querySelector(".no-warn-info"),
      });
    },
    // loading停止加载
    notLoading() {
      this.isLoading.close();
    },
    // 发送开门id给index组件--用户播放视频
    playVideo(doorId) {
      this.$emit("getDoorId", doorId);
    },
    // 告警处理
    warnHandleClick(alarmInfo) {
      this.flag = false;
      // console.log(alarmInfo);
      // this.alarmHandleFlag = true;
      this.alarmInfo = JSON.parse(JSON.stringify(alarmInfo));
      this.dialogAlarmInfo = JSON.parse(JSON.stringify(alarmInfo));
      this.$refs.refalarmDialog.dialogVisible = true; //告警弹窗
      if (alarmInfo.status != 1) return; //未处理的告警
      this.alarmDialogFlag = !this.alarmDialogFlag; // 防止弹出新的告警没声音
      // 告警声音
      if (this.isAudio) {
        if (this.isVoice) {
          this.playAudio();
        } else {
          if (!this.isPlayNextAudio) {
            this.playAudio();
            this.isPlayNextAudio = true;
            this.audio.addEventListener("ended", () => {
              //监听播放完成
              this.isPlayNextAudio = false;
            });
          }
        }
      }

      // if (alarmInfo.status == "1") {
      // this.$refs.refrightDialog.AlarmDialogVisible=true;//告警弹窗
      // this.$refs.refrightDialog.getAlarmPlay(this.dialogAlarmInfo.id) // 告警id查询告警视频列表回放
      // this.$refs.refrightDialog.getFloorById(this.dialogAlarmInfo.spaceId) // 查询平面图
      // this.$refs.refrightDialog.getgetMark(this.dialogAlarmInfo.spaceId) // 获取平面图设备标点
      // this.$refs.refrightDialog.getByTargetId(this.dialogAlarmInfo.spaceId) // 安装点id获取接警人列表
      // this.$refs.refrightDialog.GetCamera(this.dialogAlarmInfo.spaceId) // 安装点查询摄像头
      // } else {
      // this.$refs.refprocessingRecord.dialogVisible = true;
      // this.$refs.refprocessingRecord.AlarmHandleResult(this.alarmInfo.id);
      // }
    },
    clickflag() {
      this.flag = true;
    },
    // 处理成功后更新告警列表
    updateAlarmList(id) {
      let { projectData } = this;
      projectData.forEach((item) => {
        if (item.id == id) {
          item.status = 2;
        }
      });
      // 若处理的是最后一条，则关闭告警弹窗
      this.projectData = projectData;
      this.item_title = "item_title2"; //动态样式
    },
    // 处理成功后更新告警列表
    updateAlarmList2(id) {
      let { projectData } = this;
      projectData.forEach((item) => {
        if (item.id == id) {
          item.status = 2;
        }
      });
      this.projectData = projectData;
      this.item_title = "item_title2"; //动态样式
    },
    // 完结后更新告警列表
    updateAlarmList3(id) {
      let { projectData } = this;
      projectData.forEach((item) => {
        if (item.id == id) {
          item.status = 3;
        }
      });
      this.projectData = projectData;
      this.item_title = "item_title3"; //动态样式
    },
    // 取消/关闭告警处理
    changeAlarmHandleFlag() {
      this.alarmHandleFlag = false;
    },

    // 关闭告警弹窗
    closeAlarmDialog() {
      this.dialogVisible = false;
    },
    // 语音播报的函数
    handleSpeak(text) {
      speechMsg.text = text; // 文字内容: 小朋友，你是否有很多问号
      speechMsg.lang = "zh-CN"; // 使用的语言:中文
      speechMsg.volume = 1; // 声音音量：1
      speechMsg.rate = 1; // 语速：1
      speechMsg.pitch = 1; // 音高：1
      speechHandle.speak(speechMsg); // 播放
    },
    // 语音停止
    textVoiceEnd(e) {
      speechMsg.text = e;
      speechMsg.lang = "zh-CN";
      speechHandle.cancel(speechMsg);
    },

    // 连接
    MQTTconnect() {
      let _this = this;
      // this.client.onConnectionLost = this.onConnectionLost; //监听连接断开时的状态
      // this.onMessageArrived; //连接收到消息
      _this.client = mqtt.connect(_this.connectUrl, {
        clean: true,
        connectTimeout: 4000,
        reconnectPeriod: 1000,
        clientId: _this.clientId,
        username: _this.username,
        password: _this.password,
      });
      this.onConnect(); // 连接
      this.onReceive(); // 接受消息
      // this.MQTTconnect()
      // this.onDisconnect();
      // this.client.end();
      // 成功连接后触发的回调
    },
    // 监听连接
    onConnect() {
      this.client.on("connect", () => {
        // console.log("已经连接成功");
        this.isConnect = true;
        let sendMsg = JSON.stringify("hello world");
        this.client.subscribe(this.topic, {
          qos: 0,
        }); //订阅
        this.message = this.client.publish(this.topic, sendMsg);
        this.message.destinationName = this.topic; // set topic
      });
    },
    // 监听接受消息
    onReceive() {
      this.client.on("message", async (topic, message, packet) => {
        let json = this.onTransJson(message); // 字节流转json
        if (json.indexOf("hello") > -1) return;
        var msg = JSON.parse(json);
        if (msg.dataType != 1) return;
        // console.log(msg.dataContent.chatMsg.msg, "msg");
        // console.log(this.spacesManage.organizationInfo.orgId);
        // console.log(this.spacesManage.organizationInfo.orgId != msg.dataContent.chatMsg.msg.orgId);
        // console.log(this.datav.orgarr);//单位信息
        // if (this.spacesManage.organizationInfo.orgId != msg.dataContent.chatMsg.msg.orgId && this.user.roleName != 'TENANT_ADMIN') return;
        // if (this.spacesManage.organizationInfo.orgId != msg.dataContent.chatMsg.msg.orgId) return;
        this.isConnect = true; //如果接收到信息一定是在连接状态

        // 告警声音
        if (this.isAudio) {
          if (this.isVoice) {
            this.playAudio();
          } else {
            if (!this.isPlayNextAudio) {
              this.playAudio();
              this.isPlayNextAudio = true;
              this.audio.addEventListener("ended", () => {
                //监听播放完成
                this.isPlayNextAudio = false;
              });
            }
          }
        }

        // console.log(msg.dataContent.chatMsg.msg);
        msg.dataContent.chatMsg.msg.createTime = this.timestampToTime2(
          msg.dataContent.chatMsg.msg.createTime // 时间戳转换
        );
        this.projectData.unshift(msg.dataContent.chatMsg.msg);
        // console.log(msg.dataContent.chatMsg.msg);
        this.dialogAlarmInfo = msg.dataContent.chatMsg.msg; //弹窗告警信息内容--最新一条
        if (this.projectData.length > 50) {
          this.projectData.splice(0, 20);
        }
        // if(this.flag){
        this.scrollToBottom(); // 滚动条定位到最后一行
        // }
        if (this.alarmDialogType == "open") {
          this.$refs.refalarmDialog.dialogVisible = true; //告警弹窗
          this.alarmDialogFlag = !this.alarmDialogFlag;
          // this.$refs.refrightDialog.AlarmDialogVisible=true;//告警弹窗
          // this.$refs.refrightDialog.getAlarmPlay(this.dialogAlarmInfo.id) // 告警id查询告警视频列表回放
          // this.$refs.refrightDialog.getFloorById(this.dialogAlarmInfo.spaceId) // 查询平面图
          // this.$refs.refrightDialog.getgetMark(this.dialogAlarmInfo.spaceId) // 获取平面图设备标点
          // this.$refs.refrightDialog.getByTargetId(this.dialogAlarmInfo.spaceId) // 安装点id获取接警人列表
          // this.$refs.refrightDialog.GetCamera(this.dialogAlarmInfo.spaceId) // 安装点查询摄像头
        }
        this.infoSent = !this.infoSent;
        this.$store.commit("saveInfoSent", this.infoSent); //监视告警发送 +1
        this.$store.commit("saveMsgList", msg.dataContent.chatMsg.msg); //告警信息
      });
    },

    // onDisconnect() {
    //   this.client.on("close", () => {
    //     console.log("已断开连接");
    //   });
    // },
    // 字节流转json
    onTransJson(evt) {
      let encodedString = String.fromCodePoint.apply(null, new Uint8Array(evt));
      let decodedString = decodeURIComponent(escape(encodedString)); //没有这一步中文会乱码
      return decodedString;
    },
    // 获取mqtt信息
    async getMqttInfo() {
      let res = await reqClient(this.user.userId);
      //  console.log(res);
      if (res.code !== 20000) return this.$message.error(res.message);
      this.$store.commit("saveMu", res.data.rows.mu);
      this.$store.commit("saveMp", res.data.rows.mp);
      this.$store.commit("saveId", res.data.rows.mc);
    },
    async AlarmList() {
      let res = await reqAlarmList(1, 10, {
        userId: this.user.userId,
        tenantId: this.user.tenantId,
        // orgId: this.datav.orgarr.id,//测试代码 后端本地
        orgId: this.datav.orgarr.id || this.spacesManage.organizationInfo.orgId,
        roleName: this.user.roleName,
        status: "",
        imei: "",
        name: "",
        alarmType: "",
        deviceType: "",
        classMark: "",
        startTime: "",
        endTime: "",
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // this.projectData = res.data.rows.slice().reverse();//倒序
      this.projectData = res.data.rows;
    },
  },

  async mounted() {
    // console.log(this.datav.orgarr.id);
    // this.AlarmList()//告警默认请求十条
    if (process.env.NODE_ENV == "development") {
      this.port = 80;
      this.connectUrl = `ws://${this.host}:${this.port}/mqtt/ws`;
      this.useTLS = false;
    } else {
      this.port = 443;
      this.connectUrl = `wss://${this.host}:${this.port}/mqtt/wss`;
      this.useTLS = true;
    }

    await this.getMqttInfo(); // 获取mqtt信息
    this.clientId = this.datav.clientId;
    this.username = this.datav.mu;
    this.password = this.datav.mp;
    await this.MQTTconnect();
  },
  created() {
    // 响铃设置 :记住当前账号的设置 存储在本地浏览器
    if (localStorage.getItem("audio")) {
      this.audioList = JSON.parse(localStorage.getItem("audio") || []);
      this.audioList.forEach((item) => {
        if (item.id == this.user.userId) {
          this.isAudio = item.isAudio;
          return;
        }
      });
    }
  },
  destroyed() {
    this.client.end();
    this.textVoiceEnd();
  },
};
</script>

<style lang="less" scoped>
.fontSize (@px, @attr: font-size) {
  @vw: (@px / 1920) * 100;
  @{attr}: ~"@{vw}vw";
}

.lineHeight (@px, @attr: line-height) {
  @vh: (@px / 1080) * 100;
  @{attr}: ~"@{vh}vh";
}

.width (@px, @attr: width) {
  @vw: (@px / 1920) * 100;
  @{attr}: ~"@{vw}vw";
}

.height (@px, @attr: height) {
  @vh: (@px / 1080) * 100;
  @{attr}: ~"@{vh}vh";
}

.top (@px, @attr: top) {
  @vh: (@px / 1080) * 100;
  @{attr}: ~"@{vh}vh";
}

.left (@px, @attr: left) {
  @vw: (@px / 1920) * 100;
  @{attr}: ~"@{vw}vw";
}

.right (@px, @attr: right) {
  @vw: (@px / 1920) * 100;
  @{attr}: ~"@{vw}vw";
}

.marginTop (@px, @attr: margin-top) {
  @vh: (@px / 1080) * 100;
  @{attr}: ~"@{vh}vh";
}

.marginBottom (@px, @attr: margin-bottom) {
  @vh: (@px / 1080) * 100;
  @{attr}: ~"@{vh}vh";
}

.marginLeft (@px, @attr: margin-left) {
  @vw: (@px / 1920) * 100;
  @{attr}: ~"@{vw}vw";
}

.marginRight (@px, @attr: margin-right) {
  @vw: (@px / 1920) * 100;
  @{attr}: ~"@{vw}vw";
}

.warnData-item {
  height: 49vh;
  margin-top: 14px;
  overflow-y: scroll;
  position: relative;
}

.container {
  padding: 0 20px 25px 14px;
  box-sizing: border-box;
  // .height(700);
  height: 100%;
  .fontSize(16);
  display: flex;
  flex-direction: column;
  position: relative;
  // background: #061A6B;

  .div_box {
    .height(50);
    position: absolute;
    left: 14px;
    top: 0.6%;
    display: flex;
    align-items: center;

    > div {
      margin-right: 10px;
    }

    .audio-box {
      color: #00edfe;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      margin: auto;
      border-radius: 0.1vw;
      background-color: rgba(10, 20, 67, 1);
      width: 30px;

      p {
        font-size: 12px;
        cursor: pointer;
        z-index: 8000;
        text-align: center;

        &:hover {
          opacity: 0.7;
        }
      }
    }
  }

  .div_box2 {
    .height(50);
    position: absolute;
    right: 14px;
    top: 0.6%;
    display: flex;
    align-items: center;
    z-index: 999;

    > div {
      margin-right: 10px;
    }

    .audio-box {
      color: #00edfe;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      margin: auto;
      border-radius: 0.1vw;
      background-color: rgba(10, 20, 67, 1);
      width: 30px;

      p {
        font-size: 12px;
        cursor: pointer;
        z-index: 8000;
        text-align: center;

        &:hover {
          opacity: 0.7;
        }
      }
    }
  }

  .title {
    .height(43);
    width: 60%;
    margin: 0 auto;
    .fontSize(16);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    background: url("../../../assets/images/datav/head.png") no-repeat;
    background-size: 100% 100%;
    font-weight: 600;
  }

  .list {
    // height: 100%;
    // overflow: hidden;
    // overflow-y: scroll;

    .item {
      transition: all 1s;
      .fontSize(12);
      color: #fff;
      margin-bottom: 10px;
      padding: 15px 10px;
      // background: linear-gradient(180deg,
      //     #0323a9 0%,
      //     rgba(0, 17, 88, 0) 50%,
      //     #03229b 100%);
      // background: #061C7B;
      background: linear-gradient(#051f90, #041d80);

      .item_title {
        color: #ffffff;
        position: relative;
        padding-left: 13px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        &::before {
          content: "";
          position: absolute;
          width: 5px !important;
          height: 5px !important;
          top: 50% !important;
          transform: translateY(-50%);
          left: -5%;
          border-radius: 10px !important;
          left: 0px;
          background-color: #fc3758;
        }
      }

      .item_title2 {
        color: #ffffff;
        position: relative;
        padding-left: 13px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        &::before {
          content: "";
          position: absolute;
          width: 5px !important;
          height: 5px !important;
          top: 50% !important;
          transform: translateY(-50%);
          left: -5%;
          border-radius: 10px !important;
          left: 0px;
          background-color: #f08027;
        }
      }

      .item_title3 {
        color: #ffffff;
        position: relative;
        padding-left: 13px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        &::before {
          content: "";
          position: absolute;
          width: 5px !important;
          height: 5px !important;
          top: 50% !important;
          transform: translateY(-50%);
          left: -5%;
          border-radius: 10px !important;
          left: 0px;
          background-color: #1ed964;
        }
      }

      .item_box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .marginTop(10);

        > div:last-of-type {
          background: #003c9b;
          border: 1px solid #00edfe;
          border-radius: 3px;
          padding: 3px 10px;
          cursor: pointer;
          min-width: 25px;
          text-align: center;
        }
      }
    }
  }
}

.no-warn-info {
  width: 100%;
  height: 88%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  align-content: center;
  margin-top: 1.5%;
  color: #fff;
  font-size: 0.7vw;

  > img {
    width: 150px;
    height: 150px;
    margin-bottom: 10px;
  }
}

/* 动画效果 */
.mytable:hover {
  background-color: rgb(228, 230, 225);
}

.myGroup-enter,
.myGroup-leave-to {
  opacity: 0;
  transform: translateY(1vh);
}

.myGroup-enter-active,
.myGroup-leave-active {
  transition: all 1.5s ease;
}

/* v-move和v-leave-active实现删除一行，后面元素移位的动画效果 */
.myGroup-move {
  transition: all 0.6s ease-in;
}

.myGroup-leave-active {
  // position: absolute;
}

// 弹窗告警
::v-deep .el-dialog__header {
  display: none;
}

::v-deep .el-dialog__body {
  background: none;
  // background: #36499B !important;
}

::v-deep .el-dialog__footer {
  background: none !important;
  // background: #36499B !important;
}

::v-deep .el-button.el-button--default {
  background: #000f4a;
  border: 1px solid #000f4a;
  color: #d1d1d1;
}

::v-deep .el-button.el-button--primary {
  background: #000f4a !important;
  border: 1px solid #00edfe;
  color: #d1d1d1;
}

::v-deep .el-dialog {
  // background-image: linear-gradient(#364CA3,#354380, #384F92) !important;
  // background: rgba(1, 24, 46, .9) !important;
  //   background: url('../../../assets/images/datav/tanchuang.png') no-repeat !important;
  //   background-size: 100% 100% !important;
}

.elImage {
  width: 100%;
  height: auto;
}
</style>
